"""
监控指标收集
"""
import time
from typing import Dict, Any
from datetime import datetime, timedelta
from prometheus_client import Counter, Histogram, Gauge, generate_latest, CONTENT_TYPE_LATEST
from utils.logger import audit_logger


class MetricsCollector:
    """指标收集器"""
    
    def __init__(self):
        # 审核计数器
        self.audit_total = Counter(
            'content_audit_total',
            'Total number of content audits',
            ['result']  # PASS, REJECT, MANUAL
        )
        
        # 审核处理时间
        self.audit_duration = Histogram(
            'content_audit_duration_seconds',
            'Time spent on content audit',
            buckets=[0.1, 0.5, 1.0, 2.0, 5.0, 10.0]
        )
        
        # 队列长度
        self.queue_length = Gauge(
            'audit_queue_length',
            'Length of audit queue',
            ['queue_name']
        )
        
        # 算法性能指标
        self.algorithm_duration = Histogram(
            'algorithm_duration_seconds',
            'Time spent on individual algorithms',
            ['algorithm'],
            buckets=[0.01, 0.05, 0.1, 0.2, 0.5, 1.0]
        )
        
        # 违规类型计数
        self.violation_counter = Counter(
            'content_violations_total',
            'Total number of content violations',
            ['violation_type']
        )
        
        # 错误计数
        self.error_counter = Counter(
            'audit_errors_total',
            'Total number of audit errors',
            ['error_type']
        )
        
        # 系统状态
        self.system_status = Gauge(
            'audit_system_status',
            'System status (1=healthy, 0=unhealthy)',
            ['component']
        )
        
        # 内存使用情况
        self.memory_usage = Gauge(
            'audit_memory_usage_bytes',
            'Memory usage in bytes'
        )
        
        # 启动时间
        self.start_time = time.time()
        self.uptime = Gauge(
            'audit_uptime_seconds',
            'Service uptime in seconds'
        )
        
        audit_logger.info("指标收集器初始化完成")
    
    def record_audit_result(self, result: str, duration: float):
        """记录审核结果"""
        self.audit_total.labels(result=result).inc()
        self.audit_duration.observe(duration)
    
    def record_algorithm_duration(self, algorithm: str, duration: float):
        """记录算法执行时间"""
        self.algorithm_duration.labels(algorithm=algorithm).observe(duration)
    
    def record_violation(self, violation_type: str):
        """记录违规类型"""
        self.violation_counter.labels(violation_type=violation_type).inc()
    
    def record_error(self, error_type: str):
        """记录错误"""
        self.error_counter.labels(error_type=error_type).inc()
    
    def update_queue_length(self, queue_name: str, length: int):
        """更新队列长度"""
        self.queue_length.labels(queue_name=queue_name).set(length)
    
    def update_system_status(self, component: str, status: bool):
        """更新系统状态"""
        self.system_status.labels(component=component).set(1 if status else 0)
    
    def update_memory_usage(self, usage_bytes: int):
        """更新内存使用情况"""
        self.memory_usage.set(usage_bytes)
    
    def update_uptime(self):
        """更新运行时间"""
        uptime_seconds = time.time() - self.start_time
        self.uptime.set(uptime_seconds)
    
    def get_metrics(self) -> str:
        """获取Prometheus格式的指标"""
        self.update_uptime()
        return generate_latest()
    
    def get_summary(self) -> Dict[str, Any]:
        """获取指标摘要"""
        uptime_seconds = time.time() - self.start_time
        
        return {
            'uptime_seconds': uptime_seconds,
            'uptime_formatted': str(timedelta(seconds=int(uptime_seconds))),
            'total_audits': sum(self.audit_total._value.values()),
            'audit_results': {
                metric.labels['result']: metric.value 
                for metric in self.audit_total._value.values()
            },
            'avg_audit_duration': self._get_histogram_avg(self.audit_duration),
            'total_violations': sum(self.violation_counter._value.values()),
            'total_errors': sum(self.error_counter._value.values()),
            'timestamp': datetime.now().isoformat()
        }
    
    def _get_histogram_avg(self, histogram) -> float:
        """计算直方图平均值"""
        try:
            total_count = histogram._count.get()
            total_sum = histogram._sum.get()
            return total_sum / total_count if total_count > 0 else 0.0
        except:
            return 0.0


class PerformanceMonitor:
    """性能监控器"""
    
    def __init__(self, metrics_collector: MetricsCollector):
        self.metrics = metrics_collector
        self.start_time = None
        self.algorithm_name = None
    
    def __enter__(self):
        self.start_time = time.time()
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.start_time:
            duration = time.time() - self.start_time
            if self.algorithm_name:
                self.metrics.record_algorithm_duration(self.algorithm_name, duration)
            
            if exc_type:
                self.metrics.record_error(exc_type.__name__)
    
    def set_algorithm(self, name: str):
        """设置算法名称"""
        self.algorithm_name = name
        return self


# 全局指标收集器
metrics_collector = MetricsCollector()
